package com.app.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings({"unchecked","deprecation"})
public class MyFileUtil {
	
	
	/**
     * 生成UTF-8文件.
     * 如果文件内容中没有中文内容，则生成的文件为ANSI编码格式；
     * 如果文件内容中有中文内容，则生成的文件为UTF-8编码格式。
     * @param fileName 待生成的文件名（含完整路径）
     * @param fileBody 文件内容
     * @return
     */
    public static boolean writeUTFFile(String fileName,String fileBody){
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        try {
            fos = new FileOutputStream(fileName);
            osw = new OutputStreamWriter(fos, "UTF-8");
            osw.write(fileBody);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally{
            if(osw!=null){
                try {
                    osw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

	/**
	 * 删除文件夹
	 * 
	 * @param args
	 */
	public static void deleteFolder(String filePath) throws Exception {
		File folder = new File(filePath);
		try {
			String childs[] = folder.list();
			if (childs == null || childs.length <= 0) {
				folder.delete();
			}
			for (int i = 0; i < childs.length; i++) {
				String childName = childs[i];
				String childPath = folder.getPath() + File.separator + childName;
				File filePath2 = new File(childPath);
				if (filePath2.exists() && filePath2.isFile()) {
					filePath2.delete();
					//System.out.println(DateUtil.getCurrentDateTime() + "   删除文件： " + filePath2.getName());
				} else if (filePath2.exists() && filePath2.isDirectory()) {
					deleteFolder(childPath);
				}
			}
		} catch (RuntimeException e) {
			//e.printStackTrace();
		}
		folder.delete();
		//System.out.println(DateUtil.getCurrentDateTime() + "   删除文件夹： " + folder.getName());
	}

	/**
	 * 创建文件夹及文件
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static void createFolder(String filePath) throws IOException {
		String str2 = "";
		@SuppressWarnings("unused")
		String str3 = "";
		try {
			str2 = filePath.substring(0, filePath.lastIndexOf("\\") + 1);
			str3 = filePath.substring(filePath.lastIndexOf("\\"), filePath
					.length());
		} catch (RuntimeException e) {
			str2 = filePath.substring(0, filePath.lastIndexOf("/") + 1);
			str3 = filePath.substring(filePath.lastIndexOf("/") + 1, filePath
					.length());
		}
		File a = new File(str2);
		a.mkdirs();
		File b = new File(filePath);
		b.createNewFile();
	}

	// 将一个目录里的所有文件和文件夹递归取出
	
	public static List disp(String filePath, List list) {
		File file = new File(filePath);
		File[] files = file.listFiles();
		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				disp(files[i].getAbsolutePath(), list);
			}
			if (files[i].getName().indexOf(".") >= 0) {
				// System.out.println(files[i].getAbsolutePath());
				list.add(files[i].getAbsolutePath());
			}
		}
		return list;
	}
	// 将一个目录里的所有文件递归取出
	
	public static List dispFiles(String filePath, List list) {
		File file = new File(filePath);
		File[] files = file.listFiles();
		for (int i = 0; i < files.length; i++) {
			if (!files[i].isDirectory()) 
			{
				if (files[i].getName().indexOf(".") >= 0) {
					// System.out.println(files[i].getAbsolutePath());
					list.add(files[i].getAbsolutePath());
				}
			}

		}
		return list;
	}

	// 写入文件
	public static void writeFile(String data, String mbpath) throws Exception {
		FileOutputStream a2 = new FileOutputStream(mbpath);
		PrintWriter b2 = new PrintWriter(a2);
		b2.println(data);
		b2.flush();
		b2.close();
	}
	
	
	/**
	 * 编码转换，解决中文问题
	 * 
	 * 
	 * @param filename
	 * @return
	 */
	@SuppressWarnings("unused")
	public static String UTF_FileName(String filename) {
		try {
			String returnFileName = new String(filename.getBytes("GBK"),
					"8859_1");
			return returnFileName;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return filename;
		}
	}

	/***************************************************************************
	 * 文件拷贝
	 * 
	 * @param fromfile
	 * @param tofile
	 * @return
	 */
	public static String copyfile(File fromfile, String tofile) {
		try {
			/*******************************************************************
			 * 字节流操作
			 */
			createFolder(Constant.WebRoot+tofile);
			FileInputStream a1 = new FileInputStream(fromfile);// 字节流输入流
			BufferedInputStream read = new BufferedInputStream(a1);// 字节流输入管道

			FileOutputStream b1 = new FileOutputStream(Constant.WebRoot+tofile);// 字节流输出流
			BufferedOutputStream out = new BufferedOutputStream(b1);// 字节流输出管道

			byte[] buf = new byte[1024];// 准备空的二进制数组
			int len;
			while ((len = read.read(buf)) != -1) {// 读取数据到数组 所读数据如果不是空的就循环
				out.write(buf, 0, len);// 写入输出流指定文件 从0到数组这末多
				out.flush();// 刷新缓存
			}
			read.close();// 关闭输入管道
			try {
				a1.close();
			} catch (Exception e) {
			}
			out.close();// 关闭输出管道
			try {
				b1.close();
			} catch (Exception e) {
			}
			fromfile.delete();
			return tofile;
		} catch (Exception e) {
			 e.printStackTrace();
			return null;
		}
	}

	/**
	 * 更新文件数据 mode 0 直接写入 mode 1 追加方式写入 mode 2 删除文件 给出文件内容和文件路径生成文件
	 * 
	 * @param args
	 *            String[]
	 */
	public final static boolean makeFile(String fpath, String fname,
			String content, int mode, String code) {

		boolean succ = false;
		@SuppressWarnings("unused")
		File path, file;
		if (fname == null) {
			file = new File(fpath);
		} else {
			file = new File(fpath, fname);
		}
		// 删除文件
		FileOutputStream out = null;
		FileChannel fc = null;
		try {
			if (mode == 2) {
				return file.exists() ? file.delete() : false;
			}
			// 文件要加入内容.
			// 如果目录不存在则先创建目录.
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			// 如果文件不存在,则创建文件.
			if (!file.exists()) {
				file.createNewFile();
			}
			boolean append = (mode == 1);
			out = new FileOutputStream(file, append);
			fc = out.getChannel();
			fc.write(ByteBuffer.wrap(content.getBytes(code)));
			succ = true;
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				fc.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return succ;
	}

	/**
	 * 读普通文本文件 返回数据
	 * 
	 * @param String
	 *            filepath 文件路径
	 * @return String data
	 * @throws IOException
	 * @throws Exception
	 */
	public static String readTxtFile(String filepath){
		try {
			FileReader a = new FileReader(filepath);
			BufferedReader b = new BufferedReader(a);
			String str = null;
			StringBuffer str2 = new StringBuffer("");
			while ((str = b.readLine()) != null) {
				str2.append(str);
				str2.append("\r\n");
			}
			return str2.toString();
		} catch (FileNotFoundException e) {
			System.out.println(e.getLocalizedMessage());
			return "系统找不到指定的文件。";
		} catch (IOException e) {
			System.out.println(e.getLocalizedMessage());
			return "文件读取错误。";
		}
	}
	
	public static void main(String[] args) throws Exception{
		MyFileUtil.makeFile("e:/", "23.txt",
				"我们的祖国是花园 \n花园的花朵真精彩\n", 0, "utf-8");
	}
	
	public static String readTxtFile(String filepath,int key){
		try {
			FileReader a = new FileReader(filepath);
			BufferedReader b = new BufferedReader(a);
			String str = null; int num = 0;
			while ((str = b.readLine()) != null) {
				num ++;
			}
			num = (num-key);
			//System.out.println(num);
			a.close(); b.close();
			
			FileReader a2 = new FileReader(filepath);
			BufferedReader b2 = new BufferedReader(a2);
			StringBuffer str2 = new StringBuffer();
			int num2 = 0;
			while ((str = b2.readLine()) != null) {
				if(num2>=num){
					str2.append(str);
					str2.append("\r\n");
				}
				num2 ++;
			}
			a2.close(); b2.close();
			return str2.toString();
		} catch (FileNotFoundException e) {
			System.out.println(e.getLocalizedMessage());
			return "系统找不到指定的文件。";
		} catch (IOException e) {
			System.out.println(e.getLocalizedMessage());
			return "文件读取错误。";
		}
	}
	
	public static String readFileText(FileInputStream in) throws Exception {
		byte temp[]=new byte[1024];
		int b = 0;
		StringBuffer str = new StringBuffer();
		while((b=in.read(temp,0,1024))!=-1){
			str.append(new String(temp,0,b,"gb2312"));
		}
		in.close();
		return str.toString();
	}
	
	public static String readFileUTF8Text(String file) throws Exception {
		FileInputStream in = new FileInputStream(new File(file));
		byte temp[]=new byte[1024];
		int b = 0;
		StringBuffer str = new StringBuffer();
		while((b=in.read(temp,0,1024))!=-1){
			str.append(new String(temp,0,b,"utf-8"));
		}
		in.close();
		return str.toString();
	}
	
	
	/**  
     * 删除单个文件  
     * @param   fileName    被删除文件的文件名  
     * @return 单个文件删除成功返回true,否则返回false  
     */  
    public static boolean deleteFile(String fileName){   
        File file = new File(fileName);   
        if(file.isFile() && file.exists()){   
            file.delete();   
            //System.out.println("删除单个文件"+fileName+"成功！");   
            return true;   
        }else{   
           // System.out.println("删除单个文件"+fileName+"失败！");   
            return false;   
        }   
    } 


	public static byte[] toBytes(Object object){
    	java.io.ByteArrayOutputStream baos = new
    	java.io.ByteArrayOutputStream();
    	try{
    	java.io.ObjectOutputStream oos = new
    	java.io.ObjectOutputStream(baos);
    	oos.writeObject(object);
    	}catch(java.io.IOException ioe){
    	java.util.logging.Logger.global.log(java.util.logging.Level.SEVERE,
    	ioe.getMessage());
    	}
    	return baos.toByteArray();
    }
    
    public static Object toObject(byte[] bytes){
    	Object object = null;
    	try{
    	object = new java.io.ObjectInputStream(new
    	java.io.ByteArrayInputStream(bytes)).readObject();
    	}catch(java.io.IOException ioe){
    	java.util.logging.Logger.global.log(java.util.logging.Level.SEVERE,
    	ioe.getMessage());
    	}catch(java.lang.ClassNotFoundException cnfe){
    	java.util.logging.Logger.global.log(java.util.logging.Level.SEVERE,
    	cnfe.getMessage());
    	}
    	return object;
    }
    
    
    public static Map readTxtMap(String filepath){
		Map map = new HashMap();
		try {
			FileReader a = new FileReader(filepath);
			BufferedReader b = new BufferedReader(a);
			String str = null;
			String[] arr = null;
			while ((str = b.readLine()) != null) {
				System.out.println(str);
				/*arr = str.split("\t");
				if(arr.length<6){
					continue;
				}else if(str.indexOf("Serial number")!=-1){	
					break;
				}*/
			}
			/*map.put("columnLength", arr.length);
			for(int i=0;i<arr.length;i++){
				String string = arr[i];
				if(string!=null && string.trim().equals("Serial number")){
					map.put("Serial number", i);
				}else if(string!=null && string.trim().equals("Material")){
					map.put("Material", i);
				}else if(string!=null && string.trim().equals("Material Description")){
					map.put("Material Description", i);
				}else if(string!=null && string.trim().equals("Customer/Sold to")){
					map.put("Customer/Sold to", i);
				}else if(string!=null && string.trim().equals("Sold to party desc")){
					map.put("Sold to party desc", i);
				}else if(string!=null && string.trim().equals("End Customer/Ship to")){
					map.put("End Customer/Ship to", i);
				}else if(string!=null && string.trim().equals("Ship to party desc")){
					map.put("Ship to party desc", i);
				}else if(string!=null && string.trim().equals("Delivery")){
					map.put("Delivery", i);
				}else if(string!=null && string.trim().equals("Last delivery Plant")){
					map.put("Last delivery Plant", i);
				}else if(string!=null && string.trim().equals("Last Delivery PGI da")){
					map.put("Last Delivery PGI da", i);
				}else if(string!=null && string.trim().equals("Changed on")){
					map.put("Changed on", i);
				}else if(string!=null && string.trim().equals("Sold to party desc")){
					map.put("Sold to party desc", i);
				}else if(string!=null && string.trim().equals("End Customer/Ship to")){
					map.put("End Customer/Ship to", i);
				}else if(string!=null && string.trim().equals("Ship to party desc")){
					map.put("Ship to party desc", i);
				}else if(string!=null && string.trim().equals("Site Id")){
					map.put("Site Id", i);
				}else if(string!=null && string.trim().equals("Site desc.")){
					map.put("Site desc.", i);
				}
			}*/
			b.close(); a.close();
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
